package com.wholesmart.common.security;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.wholesmart.common.bean.Message;
import com.wholesmart.common.enums.SystemStatusEnum;
import com.wholesmart.common.security.crypto.SaltGenerater;
/**
 * 鉴权跳转控制器：RESTful请求则返回提示信息以及401状态码
 * 
 * @author dyw
 * @date 2019年10月11日
 */
@RestController
public class BrowserSecurityController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	/** SpringSecurity会将请求缓存到里 */
	private RequestCache requestCache = new HttpSessionRequestCache();
	@Autowired(required = false)
	private SaltGenerater saltGenerater;

	/**
	 * 当需要身份认证时跳转到这里
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/auth/require")
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	public Message requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
		SavedRequest savedRequest = requestCache.getRequest(request, response);
		if (savedRequest != null) {
			String targetUrl = savedRequest.getRedirectUrl();
			logger.info("引发跳转的请求是：" + targetUrl);
		}
		return Message.message(SystemStatusEnum.NO_AUTHORIZE.getStatue(), "访问的服务需要身份认证，请引导用户到登陆页面", null);
	}

	/**
	 * 生成16字节盐密码接口（如果需要后端生成盐密码请使用此接口）
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/auth/requireKey")
	public Message requireKey(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String salt = null;
		if (saltGenerater != null) {
			salt = saltGenerater.generater(16);
		}
		return Message.message(SystemStatusEnum.SUCCEED, salt);
	}
}
